﻿using System.Diagnostics;

namespace XsqTech.SmartOA.Application.Middleware
{
    /// <summary>
    /// 请求日志中间件
    /// </summary>
    public class RequestLogMiddleware
    {
        //下一个请求委托
        private readonly RequestDelegate _next;
        private readonly ILogger<RequestLogMiddleware> _logger; //记录日志
        //构造方法进行依赖注入
        public RequestLogMiddleware(RequestDelegate next,
        ILogger<RequestLogMiddleware> logger)
        {
            _next = next;
            _logger = logger;
        }
        /// <summary>
        /// 公开方法
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public async Task InvokeAsync(HttpContext context)
        {
            //测量代码运行消耗时间
            Stopwatch stopwatch = new Stopwatch();
            //启动服务
            stopwatch.Start();
            await _next(context); //调用下一个请求委托
            //可关服务
            stopwatch.Stop();
            string requestUrl = context.Request.Path;
            //控制台窗口输出毫秒
            _logger.LogInformation($"请求{requestUrl}，消耗了{stopwatch.ElapsedMilliseconds} 毫秒");
        }
    }
}
